package com.tcdp.controllers.view;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import com.tcdp.daos.MenuDao;
import com.tcdp.daos.WebInfoDao;
import com.tcdp.delegates.MenuDelegate;
import com.tcdp.models.Menu;

@Controller
@EnableWebMvc
public class ViewGeneralController extends AbstractViewController {

	@RequestMapping(value="/", method=RequestMethod.GET)
	public ModelAndView getIndex(){
		ModelAndView mv = new ModelAndView();
		
		WebInfoDao webInfoDao = new WebInfoDao();
		String homeUrl = webInfoDao.findByName("homeUrl");
		
		mv.setViewName("redirect:"+homeUrl);
		
		return mv;
	}
	
	@RequestMapping(value="/index", method=RequestMethod.GET)
	public ModelAndView defaultHome(){
		ModelAndView mv = new ModelAndView("Home");
		return mv;
	}
	
	@RequestMapping(value="/error", method=RequestMethod.GET)
	public ModelAndView errorPage(){
		ModelAndView mv = new ModelAndView("error/CustomError");
		return mv;
	}
	
	
	@RequestMapping(value="/header", method=RequestMethod.GET)
	public ModelAndView viewHeader(){
		ModelAndView mv = new ModelAndView("includes/Header");
		return mv;
	}

	@RequestMapping(value="/menu", method=RequestMethod.GET)
	public ModelAndView viewMenu(){
		ModelAndView mv = new ModelAndView("includes/Menu");
		
		MenuDao menuDao = new MenuDao();
		List<Menu> menus = menuDao.retrieveMenus();
		List<MenuDelegate> menuDels = new ArrayList<MenuDelegate>();
		for(Menu menu: menus){
			MenuDelegate menuDel = new MenuDelegate(menu);
			menuDels.add(menuDel);
		}
		
		mv.addObject("menus", menuDels);
		
		return mv;
	}

	@RequestMapping(value="/footer", method=RequestMethod.GET)
	public ModelAndView viewFooter(){
		ModelAndView mv = new ModelAndView("includes/Footer");
		return mv;
	}

	@ResponseBody
	@RequestMapping(value="/css/{css_url}.css", method=RequestMethod.GET, produces={"text/css"})
	public byte[] loadCSS(@PathVariable("css_url") String css_url, HttpServletResponse response, HttpServletRequest request) throws IOException{
		URL url = request.getServletContext().getResource("/WEB-INF/css/"+css_url+".css");
		int length = url.openConnection().getContentLength();
		InputStream is = url.openStream();
		byte[] data = new byte[length];
		is.read(data);

		return (data);
	}
	
}
